import common.logger as logger
from nacos import NacosClient
import socket
import requests
import traceback
from common.configuration import get_ruge_settings, get_system_settings, \
    get_nacos_settings


# 获取本机IP
LOCAL_IP = socket.gethostbyname(socket.gethostname())

# Ruge相关配置
# 环境信息
RUGE_ENV = get_ruge_settings("env")
# 安全模块服务地址
RUGE_HOST_SECURITY = f'isecurity-{RUGE_ENV}'
# 应用名称，用于注册Ruge的权限
APP_NAME = get_system_settings("app_name")
# 端口号
WEB_PORT = get_system_settings("web_port")

# Nacos服务器地址
NACOS_SERVER_ADDRESSES = get_nacos_settings("nacos_server")
# Ollama在Nacos里的服务名
NACOS_SERVICE_NAME = f"{APP_NAME}-{RUGE_ENV}"
# Nacos集群名
NACOS_CLUSTER_NAME = get_nacos_settings("nacos_cluster")
# Nacos命名空间ID
NACOS_NAMESPACE = get_nacos_settings("nacos_namespace")
# Nacos分组
NACOS_GROUP = get_nacos_settings("nacos_group")
# Nacos用户名和密码，用于认证访问Nacos服务器
NACOS_USERNAME = get_nacos_settings("nacos_username")
NACOS_PASSWORD = get_nacos_settings("nacos_password")

logger.info(f'web_port: {WEB_PORT}')
logger.info(f'env: {RUGE_ENV}')
logger.info(f'nacos_cluster: {NACOS_CLUSTER_NAME}')
logger.info(f'nacos_namespace: {NACOS_NAMESPACE}')
logger.info(f'nacos_group: {NACOS_GROUP}')
logger.debug(f'nacos_username: {NACOS_USERNAME}')
logger.debug(f'nacos_password: {NACOS_PASSWORD}')
logger.info(f'nacos_server: {NACOS_SERVER_ADDRESSES}')

# 初始化Nacos客户端
nacosClient = NacosClient(
        server_addresses=NACOS_SERVER_ADDRESSES,
        namespace=NACOS_NAMESPACE,
        username=NACOS_USERNAME,
        password=NACOS_PASSWORD,
        log_level='INFO'
    )


def registerNacos():
    """
    初始化注册Nacos
    :return:
    """
    nacosClient.add_naming_instance(
        service_name=NACOS_SERVICE_NAME,
        ip=LOCAL_IP,
        port=WEB_PORT,
        cluster_name=NACOS_CLUSTER_NAME,
        heartbeat_interval=5
    )


def find_nacos_service_host(service_name):
    """
    获取服务实例的host(随机返回一个健康实例)
    :param service_name: 服务名
    :return:
    """
    instances = nacosClient.list_naming_instance(
        service_name=service_name,
        clusters=NACOS_CLUSTER_NAME,
        namespace_id=NACOS_NAMESPACE,
        group_name=NACOS_GROUP,
        healthy_only=True
    )
    return f'{instances["hosts"][0]["ip"]}:{instances["hosts"][0]["port"]}'


def get_ruge_security_path():
    """
    获取security模块上报权限点的真实服务地址
    :return:
    """
    host = find_nacos_service_host(RUGE_HOST_SECURITY)
    return f'http://{host}/saas/security/permission/appear/{APP_NAME}'


def init_ruge_permission():
    """
    初始化Ruge权限（上报权限点）
    :return:
    """
    data = [
        {
            "bindPaths": [
                "/saas/common-mcp-server/sse"
            ],
            "operationCode": "sse",
            "operationDesc": "ruge.operation.mcp",
            "follow": 0,
            "policy": 3,
            "resource": {
                "operations": [],
                "resourceCode": "tenantCommonMCPManagement",
                "resourceDesc": "ruge.resource.tenantCommonMCPManagement",
                "resourceType": "Service",
                "serviceMapping": "common-mcp-server"
            },
            "sourceApp": APP_NAME
        }
    ]
    try:
        requests.post(url=get_ruge_security_path(), json=data)
    except Exception as e:
        logger.error(f'初始化Ruge权限失败：{e}')
        traceback.print_exc()


def init_ruge():
    """
    初始化Ruge，注册服务、上报权限
    """
    # 非本地调试，才注册服务
    if RUGE_ENV != 'local':
        try:
            # nacos注册
            logger.info('注册MCP Server到Nacos。')
            registerNacos()
        except Exception as e:
            logger.error(f'注册MCP Server到Nacos失败：{e}')
            traceback.print_exc()

        try:
            # 上报权限点
            logger.info('初始化Ruge权限（上报权限点）')
            init_ruge_permission()
        except Exception as e:
            logger.error(f'初始化Ruge权限失败：{e}')
            traceback.print_exc()
